//
//  VOLMyHouseViewController.m
//  Volver
//
//  Created by administrator on 14-9-15.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLMyHouseViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "ASIHTTPRequest.h"
#import "JSONKit.h"
#import "MJRefresh.h"

#import "VOLAppDelegate.h"
#import "VOLMyHouseCell.h"
#import "VOLMyHouseCellModel.h"
#import "VOLHouseAllInfoViewController.h"


@interface VOLMyHouseViewController ()
{
    JSONDecoder *jd;
    VOLAppDelegate *del;
    NSFileManager *manager;
    
    //数据源数组
    NSMutableArray *myHouses;
    
}

@property (weak, nonatomic) IBOutlet UILabel *noticeLabel;


@end

@implementation VOLMyHouseViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
    //初始化一些对象
    del = kGetDel;
    jd = [[JSONDecoder alloc] init];
    manager = [NSFileManager defaultManager];
    
    //添加标题
    self.title = @"我的房源";
    
    //添加菜单按钮
    addLeftNavigationBarButton();
    
    //将noticeLabel隐藏，当需要显示时再显示出来
    self.noticeLabel.hidden = YES;
    
    //设置右边添加按钮的颜色
    self.navigationItem.rightBarButtonItem.tintColor = kThemeColor;
    
    //初始化房源数组
    myHouses = [NSMutableArray array];
    
    
    //添加上拉下拉；
    [self setupRefresh];
    
    
}

#pragma mark 每次进入界面时刷新界面
-(void)viewWillAppear:(BOOL)animated{
    if (del.isRefresh == 0) {//当不是从菜单栏跳转过来时不刷新
        return;
    }
    //将是否刷新置0
    del.isRefresh = 0;
    //开始刷新
    [self.tableView headerBeginRefreshing];
}

#pragma mark - 设置上拉、下拉
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(myHouseRereshing)];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    //    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"拼命加载中...";
    
    self.tableView.footerPullToRefreshText = @"上拉加载更多数据";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载";
    self.tableView.footerRefreshingText = @"拼命加载中...";
}

#pragma mark 菜单按钮的动作
- (void)showMenu:(id)sender {
    kActionOfMenuButton;
}

#pragma mark - 重写两个刷新方法
#pragma mark 开始进入刷新状态
- (void)myHouseRereshing
{
    //    NSLog(@"开始刷新");
    //加载数据
    [self loadMyHouses];
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - 加载数据
#pragma mark 加载房屋数据
-(void)loadMyHouses{
    //    NSString *urlstr = [NSString stringWithFormat:@"%@house/searchAllHousesByUserID?userID=%d",kHTTPHome,del.currentUser.userID];
    //采用异步方式
    
    
    //发送异步请求
    NSString *urlstr = [NSString stringWithFormat:@"%@house/searchAllHousesByUserID?userID=%d",kHTTPHome,del.currentUser.userID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.delegate = self;
    [request startAsynchronous];
}



#pragma mark 跳转时初始化publishHouse
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    del.publishHouse = [[House alloc] init];
    //将当前的日期作为房屋的发布日期并记录下来
    del.publishHouse.houseDate = kGetCurrentTime;
    del.publishFacility = [[Facility alloc] init];
    NSLog(@"初始化完成");
}

#pragma mark - 代理方法
#pragma mark - 异步请求代理方法
#pragma mark 请求完成的方法：
-(void)requestFinished:(ASIHTTPRequest *)request{
    //得到返回数据
    NSData *data = [request responseData];
    if (data == nil) {
        NSLog(@"myHouseRequest------data为空");
        return;
    }
    
    NSDictionary *dic = [jd objectWithData:data];
    int status = [[dic objectForKey:@"status"] intValue];
    if (status == 0) {
        NSLog(@"myHouse------查询失败");
        //        return;
    }else{
        //得到房屋数组
        NSArray *array = [dic objectForKey:@"house"];
        
        //首先判断favoriteHouses是否为空，如果不是，先清空(注意：清空位置必须在这里，否则会引起程序崩掉，因为当执行刷新时，tableView上的cell还在显示，而且是在动的，这个时候会调用cellForRow方法的，如果在前面一开始就清空的话，执行方法时就没有对应的数据了，所以只能在确定请求到数据以后，要在它重新加载时，再清空)
        if (myHouses.count != 0) {
            [myHouses removeAllObjects];
        }
        
        //遍历这个数组，将内容取出
        for (NSDictionary *obj in array) {
            VOLMyHouseCellModel *model = [[VOLMyHouseCellModel alloc] init];
            
            model.houseID = [[obj objectForKey:@"house_id"] intValue];
            model.houseImageName = [obj objectForKey:@"image_name"];
            model.houseTitle = [obj objectForKey:@"house_title"];
            kGetHouseType(model.houseType, [[obj objectForKey:@"house_type"] intValue]);
            
            NSString *province = [obj objectForKey:@"house_province"];
            NSString *city = [obj objectForKey:@"house_city"];
            NSString *street = [obj objectForKey:@"house_street"];
            model.houseAddress = [NSString stringWithFormat:@"%@%@%@",province,city,street];
            
            model.houseExpirationdate = [[obj objectForKey:@"house_expirationdate"] doubleValue];
            
            //添加到myHouse中去
            [myHouses addObject:model];
        }
        
        //判断是否有收藏的房屋
        if (myHouses.count == 0) {
            //显示提示Label
            self.noticeLabel.text = @"显示您所发布的房子";
            self.noticeLabel.textColor = kThemeColor;
            self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            self.noticeLabel.hidden = NO;
        }else{
            self.noticeLabel.hidden = YES;
        }
    }
    
    //刷新tableView
    [self.tableView reloadData];
    //停止刷新动作
    [self.tableView headerEndRefreshing];
}


#pragma mark 请求失败的方法：
-(void)requestFailed:(ASIHTTPRequest *)request{
    [self.tableView headerEndRefreshing];
    NSLog(@"MyHouse-----请求失败");
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return myHouses.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"myHouseCell";
    VOLMyHouseCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    
    //    NSLog(@"count = %d",myHouses.count);
    //设置cell上的label的字体颜色
    cell.houseTypeLabel.textColor = kPriceLabelColor;
    cell.houseAddressLabel.textColor = kPriceLabelColor;
    
    //旋转
    cell.cellNoticeLabel.transform = CGAffineTransformMakeRotation(M_PI_4/2);
    
    VOLMyHouseCellModel *model = myHouses[indexPath.row];
    cell.houseTitleLabel.text = model.houseTitle;
    cell.houseTypeLabel.text = model.houseType;
    cell.houseAddressLabel.text = model.houseAddress;
    
//    cell.houseImageView.transform = CGAffineTransformMakeRotation(M_PI_4);
    //加载图片
    //先判断是否有这个路径存在，如果没有要先创建
    NSString *imageDocumentPath = [NSString stringWithFormat:@"%@%d/houseImages/%d",kGetDocumentsPath,del.currentUser.userID,model.houseID];
    if (![manager fileExistsAtPath:imageDocumentPath]) {
        [manager createDirectoryAtPath:imageDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //先从本地查找是否已有图片
    NSString *imagePath = [NSString stringWithFormat:@"%@%d/houseImages/%d/%@",kGetDocumentsPath,del.currentUser.userID,model.houseID,model.houseImageName];
    if ([manager fileExistsAtPath:imagePath]) {
        cell.houseImageView.image = [UIImage imageWithContentsOfFile:imagePath];
    }
    else{
        [self loadImage:model.houseImageName houseID:model.houseID indexPath:indexPath imagePath:imagePath];
    }
    
    //判断房屋是否过期
    double isDue = model.houseExpirationdate - kGetCurrentTime;
    //将下面这个属性置为NO，这样在旋转的时候大小就不会变了
    cell.cellNoticeLabel.autoresizingMask = UIViewAutoresizingNone;
    
    if (isDue < 0) {//过期
        //设置过期提示字体颜色，内容
        cell.cellNoticeLabel.textColor = kThemeColor;
        cell.cellNoticeLabel.text = @"已过期";
        cell.cellNoticeLabel.hidden = NO;
        //过期房屋houseTitleLabel的字体变颜色
        cell.houseTitleLabel.textColor = kPriceLabelColor;
        //houseImageView透明度降为一半
        cell.houseImageView.alpha = 0.5;
        
        //设置完毕直接返回 cell
        return cell;
    }else{
        
        //即将过期提示
        if (isDue < kOneDaySeconds * 10) {
            //如果还有3天过期，显示“即将过期”提示
            //设置提示字体颜色，内容
            cell.cellNoticeLabel.textColor = kOrangeColor;
            cell.cellNoticeLabel.text = @"即将过期";
            cell.cellNoticeLabel.hidden = NO;
        }else{
            cell.cellNoticeLabel.hidden = YES;
        }
        
        //没有过期的时候，将houseImageView透明度复原，cellNoticeLable隐藏，将houseTitleLabel的字体颜色恢复
        cell.houseImageView.alpha = 1;
        cell.houseTitleLabel.textColor = kBlackColor;
        
    }
    
    
    return cell;
}

#pragma mark 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

#pragma mark 点击某一个cell时
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //取消选中时的背影色
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //点击某个cell时跳转
    VOLHouseAllInfoViewController *houseAllInfo = [self.storyboard instantiateViewControllerWithIdentifier:@"houseAllInfoController"];
    //传递参数
    houseAllInfo.sourceFrom = 1;
    houseAllInfo.houseID = [myHouses[indexPath.row] houseID];
    
    [self.navigationController pushViewController:houseAllInfo animated:YES];
}

#pragma mark 加载图片
-(void)loadImage:(NSString *)imageName houseID:(int)houseID indexPath:(NSIndexPath *)indexPath imagePath:(NSString *)imagePath{
    
    //开启新线程加载图片
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //组装image的url
        NSString *urlstr = [NSString stringWithFormat:@"%@%d/%@",kHouseImageHome,houseID,imageName];
        NSURL *url = [NSURL URLWithString:urlstr];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        if (image !=nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                VOLMyHouseCell *cell = (VOLMyHouseCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                cell.houseImageView.image = image;
                //本地保存图片
                [data writeToFile:imagePath atomically:YES];
            });
        }
        else{
            NSLog(@"没有图片");
        }
    });
    
}

@end
